package com.example.springbootdemo.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.util.Random;

/**
 * @author xuwangqi
 * @date 2021/5/26 11:24
 * MD5工具类
 **/
@Slf4j
public class MD5Utils {
    /***
     * MD5加码 生成32位md5码
     */
    public static String string2Md5(String inStr) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            log.error("{}", e.getMessage(), e);
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte b : md5Bytes) {
            int val = ((int) b) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }
    /*============================================下面这个是加盐混淆的mdk5,48位，是32位的密码加16位的盐，每隔3个生成而来===================*/

    /**
     * 生成混入随机盐之后的密文
     *
     * @param password 明文密码
     * @return 混入随机盐之后的密文
     */
    public static String generate(String password) {
        if (password == null) {
            return null;
        }
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        String salt = sb.toString();
        //将“盐”加到明文中，并生成新的MD5码
        password = md5Hex(password + salt);
        if (password == null) {
            return null;
        }
        //将“盐”混入新生成的MD5码中
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }

    /**
     * 验证明文的密码和 密文的md5码是否相同
     *
     * @param password 明文
     * @param md5      加盐后的密文
     * @return 相同为true，反之false
     */
    public static boolean verify(String password, String md5) {
        //先从MD5码中取出之前加的“盐”和加“盐”后生成的MD5码
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        try {
            for (int i = 0; i < 48; i += 3) {
                cs1[i / 3 * 2] = md5.charAt(i);
                cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
                cs2[i / 3] = md5.charAt(i + 1);
            }
            String salt = new String(cs2);
            return new String(cs1).equals(md5Hex(password + salt));
        } catch (Exception e) {
            log.error("密码校验错误:{}", e.getMessage());
            throw new BusinessException(ResultEnum.AuthError);
        }

        //比较二者是否相同
    }

    /**
     * @param str 要加密的字符串
     * @return 加密后的字符串
     */
    private static String md5Hex(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(str.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

}
